var drag = {};

drag.is_ie = document.all;
drag.enabled = false;
drag.obj = null;
drag.x = 0;
drag.y = 0;
drag.move_func = null;
drag.release_func = null;
drag.start_func = null;
drag.x_start = 0;
drag.y_start = 0;
drag.container_class = "drag_box";
drag.handle_class = "drag_handle";
drag.exclude_class = "drag_exclude";

drag.lock_x = false;
drag.lock_y = false;

drag.move = function ( e ) 
{
	if ( ! drag.enabled ) return;

	var xpos, ypos;
	var evt = drag.is_ie ? event : e;

	// document.title = "XSTART: " + drag.x_start + " - CX: " + evt.clientX + " - DX: " + drag.x;

	xpos = evt.clientX;
	ypos = evt.clientY;

	if ( ! drag.lock_y ) drag.obj.style.top = ( ypos - drag.y_start ) + "px";
	if ( ! drag.lock_x ) drag.obj.style.left = ( xpos - drag.x_start ) + "px";

	/*if ( ! drag.obj._dragged )
	{
		drag.obj._dragged = true;
		if ( drag.start_func ) drag.start_func ( drag.obj );
	}*/

	if ( drag.move_func ) drag.move_func ( drag.obj, xpos, ypos );
};

drag.start = function ( e ) 
{
	var evt = drag.is_ie ? event : e;

	var firedobj   = drag.is_ie ? evt.srcElement : evt.target;
	var topelement = drag.is_ie ? "BODY" : "HTML";

	if ( ! firedobj || firedobj == null || firedobj == "" || ! firedobj.tagName || firedobj.tagName == "" || firedobj.tagName == 'HTML' ) return;

	while ( firedobj.tagName != topelement &&
		( firedobj.className.indexOf ( drag.handle_class ) == -1 ) &&
		( firedobj.className.indexOf ( drag.exclude_class ) == -1 ) )
			firedobj = drag.is_ie ? firedobj.parentElement : firedobj.parentNode;

	if ( firedobj.className.indexOf ( drag.handle_class ) != -1 )
	{
		while ( firedobj.tagName != topelement && ( firedobj.className.indexOf ( drag.container_class ) == -1 ) )
			firedobj = drag.is_ie ? firedobj.parentElement : firedobj.parentNode;

		drag.enabled = true;
		drag.obj = firedobj;
		drag.x = evt.clientX;
		drag.y = evt.clientY;
		//drag.obj._dragged = false;
		document.onmousemove = drag.move;

		var start_x = 0;
		var start_y = 0;
		var obj = drag.obj;
		while ( obj && obj.tagName != topelement )
		{
			start_x += obj.offsetLeft;
			start_y += obj.offsetTop;
			obj = obj.offsetParent;
		}

		drag.x_start = drag.x - start_x;
		drag.y_start = drag.y - start_y;

		if ( drag.start_func ) drag.start_func ( drag.obj );

		drag.obj.parentNode.removeChild ( drag.obj );
		document.body.appendChild ( drag.obj );

		drag.obj.style.position = "absolute";
		drag.obj.style.top = ( drag.y - drag.y_start ) + "px";
		drag.obj.style.left = ( drag.x - drag.x_start ) + "px";
	}
}

drag.stop = function ()
{
	if ( ! drag.obj ) return;

	drag.enabled = false;

	if ( drag.release_func ) drag.release_func ( drag.obj );

	//drag.obj._dragged = false;

	drag.obj = false;
};

document.onmousedown = drag.start;
document.onmouseup = drag.stop;

